package com.study.example.service.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * Created by User on 2017/9/14.
 */
@Primary
@Service
public class JedisPoolImpl implements IRedisService {

    private static final Logger log = LoggerFactory.getLogger(JedisPoolImpl.class);

    @Autowired
    private JedisPool jedisPool;

    @Override
    public void set(String key, String value) {
        Jedis resource = null;
        try {
            resource = jedisPool.getResource();
            resource.set(key, value);
            log.info("Redis set success key:" + key + " value:" + value);
        } catch (Exception e) {
            log.error("Redis set error key:" + key + " value:" + value);
            log.error(e.getMessage());
        } finally {
            if (resource != null)
                resource.close();
        }
    }

    @Override
    public String get(String key) {
        Jedis resource = null;
        String value = null;
        try {
            resource = jedisPool.getResource();
            value = resource.get(key);
            log.info("Redis get success key:" + key + " value:" + value);
        } catch (Exception e) {
            log.error("Redis get error key:" + key);
            log.error(e.getMessage());
        } finally {
            if (resource != null)
                resource.close();
        }

        return value;
    }

    public void test() {

    }

}
